package com.yupi.springbootinit.config;

import com.yupi.springbootinit.common.ErrorCode;
import com.yupi.springbootinit.exception.BusinessException;
import org.jetbrains.annotations.NotNull;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;

/**
 * ClassName: ThreadPoolExecutorConfig
 * Package: com.yupi.springbootinit.config
 * Description: 线程池的配置
 *
 * @Author:
 * @Create: 2024/4/2 - 13:47
 * @Version: v1.0
 */
@Configuration
public class ThreadPoolExecutorConfig {


    @Bean
    public ThreadPoolExecutor threadPoolExecutor() {

        ThreadFactory threadFactory = new ThreadFactory() {
            private int count = 1;

            @Override
            public Thread newThread(@NotNull Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("线程" + count);
                count++;
                return thread;
            }
        };


        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 4, 1000, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(3), threadFactory, new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "队列已满");
            }
        });
        return threadPoolExecutor;
    }
}
